import watermark from '../../../../common/watermark.js';
import salesdailyApi from "../../../../common/api/bi/salesdaily.api.js";
import WxcodeApi from '../../../../common/api/account/wxcode.api.js';
import doT from '../../../../../vendor/template/doT.js';

let _json = Utils.ParsingUrl(window.location);
let _today = moment().format('YYYY/MM/DD');

let insaleInfo = [], outsaleInfo = [], inCount = [], outCount = [], mySwiper;
const template = doT.template($('#sale-template').text());

(function (window, document, $) {
    new Vue({
        el: '#salesdaily-app',
        data() {
            return {
                showDatePicker: false,
                queryDate: moment().subtract(1, 'days').format('YYYY/MM/DD'),
                timer: null,
            }
        },
        computed: {
            queryDateStr({ queryDate }) {
                return moment(queryDate).format('YYYY-MM-DD')
            }
        },
        created() {
            $(`#salesdaily-app`).removeClass('d-none')
            if (Utils.IsNotNull(_json.bizDate)) {
                this.queryDate = moment(_json.bizDate).format('YYYY/MM/DD');
            } else {
                this.queryDate = moment(_json.bizDate).subtract(1, 'days').format('YYYY/MM/DD');
            }
            $('body').attr('data-weui-theme', 'light'); // 强制光明模式
        },
        mounted() {
            this.initialize();
            this.watermarkBgImg();
            this.onClickTap();
            this.initSwiper();
            this.lineEcarts();
            this.initSlide();
            this.pullLoad();
        },
        methods: {
            //初始化
            async initialize() {
                $('#thisYear,#year').text(moment().format('YYYY'));
                //年度销量信息查询
                let yearTotal = await salesdailyApi.getTotalYear(moment().format('YYYY'));
                $('#allCountYear').text(Utils.toThousands(yearTotal.allCount, 0));
                $('#inCountYear').text(Utils.toThousands(yearTotal.inCount, 0));
                $('#ouCountYear').text(Utils.toThousands(yearTotal.ouCount, 0));
                //销售合计
                let dayInfo = [moment(this.queryDate).format('YYYY/MM/DD'),
                moment(this.queryDate).subtract(1, 'days').format('YYYY/MM/DD'),
                moment(this.queryDate).subtract(2, 'days').format('YYYY/MM/DD'),
                moment(this.queryDate).subtract(3, 'days').format('YYYY/MM/DD'),
                moment(this.queryDate).subtract(4, 'days').format('YYYY/MM/DD'),
                moment(this.queryDate).subtract(5, 'days').format('YYYY/MM/DD'),
                moment(this.queryDate).subtract(6, 'days').format('YYYY/MM/DD'),


                ]
                for (var i = 0; i < dayInfo.length; i++) {
                    let day = {
                        "bizDate": dayInfo[i]
                    }
                    let content = await salesdailyApi.postSaleTotal(day);
                    let inside = content.find(s => s.isInternalCompany == true);//内销
                    let exportSale = content.find(s => s.isInternalCompany == false);//外销

                    let totalCount = 0, totalAvgWeight = 0.00, totalUnitPrice = 0.00;
                    if (Utils.IsNotNull(inside) && Utils.IsNotNull(exportSale)) {
                        totalCount = Utils.toThousands(parseInt(inside.count) + parseInt(exportSale.count), 0);
                        totalAvgWeight = Utils.toThousands((parseFloat(inside.avgWeight) + parseFloat(exportSale.avgWeight)) / 2);
                        totalUnitPrice = Utils.toThousands((parseFloat(inside.unitPrice) + parseFloat(exportSale.unitPrice)) / 2);
                    } else if (Utils.IsNotNull(inside) && !Utils.IsNotNull(exportSale)) {
                        totalCount = Utils.toThousands(parseInt(inside.count) + parseInt(0), 0);
                        totalAvgWeight = Utils.toThousands((parseFloat(inside.avgWeight) + parseFloat(0)));
                        totalUnitPrice = Utils.toThousands((parseFloat(inside.unitPrice) + parseFloat(0)));
                    } else if (!Utils.IsNotNull(inside) && Utils.IsNotNull(exportSale)) {
                        totalCount = Utils.toThousands(parseInt(0) + parseInt(exportSale.count), 0);
                        totalAvgWeight = Utils.toThousands((parseFloat(0) + parseFloat(exportSale.avgWeight)));
                        totalUnitPrice = Utils.toThousands((parseFloat(0) + parseFloat(exportSale.unitPrice)));
                    } else {
                        totalCount = Utils.toThousands(parseInt(0) + parseInt(0), 0);
                        totalAvgWeight = Utils.toThousands((parseFloat(0) + parseFloat(0)));
                        totalUnitPrice = Utils.toThousands((parseFloat(0) + parseFloat(0)));
                    }
                    $('#livestock-loop').append(template({
                        seq: [i] + 1,
                        bizDate: moment(dayInfo[i]).format('YYYY-MM-DD'),
                        inside: inside,
                        exportSale: exportSale,
                        totalCount: totalCount,
                        totalAvgWeight: totalAvgWeight,
                        totalUnitPrice: totalUnitPrice
                    }));
                    this.pieLoad([i] + 1);
                }

                //let day = {
                //    "bizDate": moment(this.queryDate).format('YYYY/MM/DD')
                //}
                //salesdailyApi.postSaleTotal(day).then(res => {
                //    if (Utils.IsNotNull(res)) {
                //        let inside = res.find(s => s.isInternalCompany == true);//内销
                //        let exportSale = res.find(s => s.isInternalCompany == false);//外销
                //        if (Utils.IsNotNull(inside)) {
                //            $('#inCount').text(Utils.toThousands(inside.count, 0));
                //            $('#inAvgWeight').text(Utils.toThousands(inside.avgWeight));
                //            $('#inUnitPrice').text(Utils.toThousands(inside.unitPrice));
                //        }
                //        if (Utils.IsNotNull(exportSale)) {
                //            $('#outCount').text(Utils.toThousands(exportSale.count, 0));
                //            $('#outAvgWeight').text(Utils.toThousands(exportSale.avgWeight));
                //            $('#outUnitPrice').text(Utils.toThousands(exportSale.unitPrice));
                //        }
                //    } else {
                //        $('.sale-summary').text('0.00');
                //        $('#unitPrice').text('0');
                //    }
                //    $('#count').text(Utils.toThousands(parseInt($('#inCount').text().replace(',', '')) + parseInt($('#outCount').text().replace(',', '')), 0));
                //    $('#avgWeight').text(Utils.toThousands(parseFloat($('#inAvgWeight').text().replace(',', '') + $('#outAvgWeight').text().replace(',', ''))));
                //    $('#unitPrice').text(Utils.toThousands((parseFloat($('#inUnitPrice').text().replace(',', '')) + parseFloat($('#outUnitPrice').text().replace(',', ''))) / 2));
                //    this.pieLoad();
                //});
            },
            // 返回主页
            returnHome() {
                location.href = '../../../main.html'
            },
            // 点击日期选择
            clickDate() {
                let that = this
                that.showDatePicker = true
                let defaultValue = this.queryDate.split('/')
                weui.datePicker({
                    defaultValue,
                    container: 'body',
                    onConfirm: function (result) {
                        mySwiper.slideTo(0, 500, true);//回到第一个slide
                        _today = result.map(item => item.value).join('/');
                        that.queryDate = result.map(item => item.value).join('/');
                        that.showDatePicker = false
                        that.initialize();
                        that.initSwiper();
                    },
                    onClose: function () {
                        that.showDatePicker = false
                    },
                    id: 'datePicker'
                });
            },
            // 改变日期 单天
            changeOneDay(type) {
                let queryDate = moment(this.queryDate)
                if (type === 'pre') {
                    queryDate = queryDate.subtract(1, 'days')
                } else {
                    queryDate = queryDate.add(1, 'days')
                }
                _today = queryDate.format('YYYY/MM/DD');
                this.queryDate = queryDate.format('YYYY/MM/DD');
                this.initialize();
                this.initSwiper();
                mySwiper.slideTo(0, 500, false);//回到第一个slide
            },
            //饼图
            pieLoad(seq) {
                let out = (parseInt($(`#outCount${seq}`).text().replace(',', '')) / parseInt($(`#count${seq}`).text().replace(',', ''))) * 100;
                let int = (parseInt($(`#inCount${seq}`).text().replace(',', '')) / parseInt($(`#count${seq}`).text().replace(',', ''))) * 100;
                var chartDom = document.getElementById(`curinventory${seq}`);
                var myChart = echarts.init(chartDom);
                var option = {
                    title: {
                        text: '',
                        subtext: '',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'item'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left'
                    },
                    series: [
                        {
                            type: 'pie',
                            radius: '50%',
                            data: [
                                { value: Utils.toThousands(out || 0), name: `外销` },
                                { value: Utils.toThousands(int || 0), name: '内销' }
                            ],
                            label: {
                                formatter: function (data) {
                                    return `${data.name.replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,')}\n(${data.percent.toFixed(2)}%)`
                                }
                            },
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ]
                };
                option && myChart.setOption(option);
            },
            //趋势图
            async initSwiper() {
                insaleInfo = [], outsaleInfo = [], inCount = [], outCount = [];
                let parameter = {
                    "startDate": moment(this.queryDate).subtract(6, 'days').format('YYYY/MM/DD'),
                    "endDate": moment(this.queryDate).format('YYYY/MM/DD')
                }
                let saleorderrpts = await salesdailyApi.postDayList(parameter);

                let dayInfo = [
                    moment(this.queryDate).subtract(6, 'days').format('MM/DD'),
                    moment(this.queryDate).subtract(5, 'days').format('MM/DD'),
                    moment(this.queryDate).subtract(4, 'days').format('MM/DD'),
                    moment(this.queryDate).subtract(3, 'days').format('MM/DD'),
                    moment(this.queryDate).subtract(2, 'days').format('MM/DD'),
                    moment(this.queryDate).subtract(1, 'days').format('MM/DD'),
                    moment(this.queryDate).format('MM/DD')
                ]
                //内销
                let insale = saleorderrpts.filter(s => s.isInternalCompany == true);
                for (var i = 0; i < dayInfo.length; i++) {
                    let inData = insale.find(x => moment(x.bizDate).format('MM/DD').indexOf(dayInfo[i]) !== -1);
                    if (Utils.IsNotNull(inData)) {
                        insaleInfo.push(inData.unitPrice);
                        inCount.push(inData.count);
                    } else {
                        insaleInfo.push(0);
                        inCount.push(0);
                    }
                }

                //外销
                let outsale = saleorderrpts.filter(s => s.isInternalCompany == false);
                for (var i = 0; i < dayInfo.length; i++) {
                    let outData = outsale.find(x => moment(x.bizDate).format('MM/DD').indexOf(dayInfo[i]) !== -1);
                    if (Utils.IsNotNull(outData)) {
                        outsaleInfo.push(outData.unitPrice);
                        outCount.push(outData.count);
                    } else {
                        outsaleInfo.push(0);
                        outCount.push(0);
                    }
                }
                this.lineEcarts(dayInfo);

                mySwiper = new Swiper('.swiper-container',
                    {
                        speed: 1000,//播放速度
                        //autoHeight: true,
                        loop: false,//循环 最后面一个往后面滑动会滑到第一个
                        setWrapperSize: true,
                        pagination: {//分页器
                            el: '.swiper-pagination',
                            clickable: true,
                        },
                        effect: 'slide',//动画效果
                        on: {
                            slideChangeTransitionStart: function () {
                                switch (this.activeIndex) {
                                    case 1:
                                        barEcarts();
                                        break;
                                }
                            }
                        },
                    },
                );
            },
            //折线图
            lineEcarts(dayInfo) {
                var chartDom = document.getElementById('salesTrend');
                var myChart = echarts.init(chartDom);
                var option = {
                    title: {
                        text: '总均价趋势',
                        subtext: '单位：元/kg',
                        textStyle: {
                            fontSize: 15
                        }
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function (params) {
                            let result = '';
                            params.forEach(item => {
                                result += `${item.seriesName}: ${item.value}元/kg<br>`;
                            });
                            return result;
                        }
                    },
                    legend: {
                        data: ['内销', '外销'],
                        left: 'right'
                    },
                    grid: {
                        left: '10%',
                        right: '10%',
                        bottom: '15%',
                        top: '20%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        axisLabel: {
                            rotate: 45,
                            interval: 1
                        },
                        data: dayInfo
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            name: '内销',
                            type: 'line',
                            label: {
                                normal: {
                                    show: true,
                                    position: 'bottom',
                                    distance: 5,
                                    formatter: function (params) {
                                        return params.value.toFixed(2);
                                    },
                                    textStyle: {
                                        fontSize: 10
                                    }
                                }
                            },
                            labelLayout: {
                                hideOverlap: true // 避免标签重叠
                            },
                            data: insaleInfo
                        },
                        {
                            name: '外销',
                            type: 'line',
                            label: {
                                normal: {
                                    show: true,
                                    position: 'top',
                                    distance: 5,
                                    formatter: function (params) {
                                        return params.value.toFixed(2);
                                    },
                                    textStyle: {
                                        fontSize: 10
                                    }
                                }
                            },
                            labelLayout: {
                                hideOverlap: true // 避免标签重叠
                            },
                            data: outsaleInfo
                        }
                    ]
                };
                option && myChart.setOption(option);
            }
            ,
            //水印信息
            async watermarkBgImg() {
                let _userInfo = JSON.parse(Utils.GetSessionStorage("SNAccountEply")) || JSON.parse(Utils.GetSessionStorage("SNLoginUserInfo"));

                //if (!Utils.IsNotNull(_userInfo)) {
                //    let json = await WxcodeApi.queryUserName();
                //    Utils.SetSessionStorage("SNAccountEply", json);
                return WxcodeApi.queryUserInfo().then(res => {
                    watermark.set(res.name + res.numCode);// 水印
                }).catch(_ => {
                    watermark.set(_userInfo.un);// 水印
                });
                //}
                //EmployeeMgtApi.getLoginUserToStaff(Utils.GetQueryString('state') || '').then(res => {
                //watermark.set((_userInfo.curUserName || "") + res.code);// 水印
                //}).catch(_ => {
                //watermark.set(_userInfo.un || _userInfo.name);// 水印
                //});
            },
            //点击事件
            onClickTap() {
                //内销 客户
                $(document).on('click', '.insideSales', function (e) {
                    let time = $(`.echoTime${$(this).attr('id')}`).text();
                    //let time = $('.echoTime').text().replace("年", "/").replace("月", "/").replace("日", "");
                    location.href = `../livestock/insidesales.html?bizDate=${moment(time).format('YYYY/MM/DD')}`;
                });
                //外销 大区
                $(document).on('click', '.exportSales', function (e) {
                    let time = $(`.echoTime${$(this).attr('id')}`).text();
                    //let time = $('.echoTime').text().replace("年", "/").replace("月", "/").replace("日", "");
                    location.href = `../livestock/outsalesdaily.html?bizDate=${moment(time).format('YYYY/MM/DD')}`;
                });
            },
            //下拉加载
            initSlide() {
                //分别设置滑动距离，开始位置，结束位置，和模拟数据的定时器
                let disY, startY, endY, timer, t, pullheight;
                let that = this;
                // 触摸开始
                $('#salesdaily-pull').on('touchstart', function (e) {
                    startY = e.originalEvent.changedTouches[0].pageY;//开始时的坐标
                });
                // 移动中
                $('#salesdaily-pull').on('touchmove', function (e) {
                    endY = e.originalEvent.changedTouches[0].pageY;
                    disY = endY - startY;//移动后的坐标减去开始坐标，滑动距离。
                    if (isTop() && disY > 0) {
                        e.preventDefault();
                    }
                    if (disY < 60) {
                        $('#pull-down').css({
                            height: disY + 'px'//父盒子的高度随着滑动距离变化，有最大值。
                        });
                    } else {
                        $('#pull-down').css({
                            height: 60 + 'px'//父盒子的最大高度
                        });
                    }
                    // 结束时
                    $('#salesdaily-pull').on('touchend', function (e) {
                        clearInterval(timer);
                        endY = e.originalEvent.changedTouches[0].pageY;
                        disY = endY - startY;
                        if (isTop() && disY > 0) {
                            timer = setInterval(function () {
                                $('#pull-down').css({
                                    height: 0 + 'px',//松手后的返回。
                                });
                                clearInterval(timer);
                                let queryDate = moment(_today);
                                queryDate = queryDate.subtract(1, 'days');
                                _today = queryDate.format('YYYY/MM/DD');
                                that.queryDate = queryDate.format('YYYY/MM/DD');
                                that.initialize();
                                that.initSwiper();
                            }, 300);
                        } else {
                            $('#pull-down').css({
                                height: 0 + 'px',//松手后的返回。
                            });
                        }
                        $('#salesdaily-pull').off('touchend')
                    })
                });
            },
            //上划加载
            pullLoad() {
                let that = this;
                // 监听滚动的父容器
                $("body").infinite().on("infinite", function () {
                    let self = this;
                    if (self.loading) return;
                    self.loading = true;
                    setTimeout(async function () {
                        let queryDate = moment(_today);
                        queryDate = queryDate.subtract(1, 'days');
                        _today = queryDate.format('YYYY/MM/DD');
                        that.queryDate = queryDate.format('YYYY/MM/DD');
                        //that.initialize();
                        //that.initSwiper();
                        let lastDiv = $('.report-contents-item-box').last();
                        let a = moment(lastDiv.attr('data-bizdate'));
                        let b = a.subtract(1, 'days');
                        let c = b.format('YYYY/MM/DD');

                        let day = {
                            "bizDate": c
                        }
                        let content = await salesdailyApi.postSaleTotal(day);
                        let inside = content.find(s => s.isInternalCompany == true);//内销
                        let exportSale = content.find(s => s.isInternalCompany == false);//外销
                        let totalCount = 0, totalAvgWeight = 0.00, totalUnitPrice = 0.00;
                        if (Utils.IsNotNull(inside) && Utils.IsNotNull(exportSale)) {
                            totalCount = Utils.toThousands(parseInt(inside.count) + parseInt(exportSale.count), 0);
                            totalAvgWeight = Utils.toThousands(parseInt(inside.avgWeight) + parseInt(exportSale.avgWeight));
                            totalUnitPrice = Utils.toThousands((parseFloat(inside.unitPrice) + parseFloat(exportSale.unitPrice)) / 2);
                        } else if (Utils.IsNotNull(inside) && !Utils.IsNotNull(exportSale)) {
                            totalCount = Utils.toThousands(parseInt(inside.count) + parseInt(0), 0);
                            totalAvgWeight = Utils.toThousands(parseInt(inside.avgWeight) + parseInt(0));
                            totalUnitPrice = Utils.toThousands((parseFloat(inside.unitPrice) + parseFloat(0)) / 2);
                        } else if (!Utils.IsNotNull(inside) && Utils.IsNotNull(exportSale)) {
                            totalCount = Utils.toThousands(parseInt(0) + parseInt(exportSale.count), 0);
                            totalAvgWeight = Utils.toThousands(parseInt(0) + parseInt(exportSale.avgWeight));
                            totalUnitPrice = Utils.toThousands((parseFloat(0) + parseFloat(exportSale.unitPrice)) / 2);
                        } else {
                            totalCount = Utils.toThousands(parseInt(0) + parseInt(0), 0);
                            totalAvgWeight = Utils.toThousands(parseInt(0) + parseInt(0));
                            totalUnitPrice = Utils.toThousands((parseFloat(0) + parseFloat(0)) / 2);
                        }


                        $('#livestock-loop').append(template({
                            seq: lastDiv.attr('id') + 1,
                            bizDate: moment(c).format('YYYY-MM-DD'),
                            inside: inside,
                            exportSale: exportSale,
                            totalCount: totalCount,
                            totalAvgWeight: totalAvgWeight,
                            totalUnitPrice: totalUnitPrice
                        }));
                        that.pieLoad(lastDiv.attr('id') + 1);

                        self.loading = false;
                        //页面滑到顶部
                        //document.body.scrollTop = document.documentElement.scrollTop = 0;
                    }, 1000);   //模拟延迟
                });
            }
        },
    });

    //柱状图
    const barEcarts = () => {
        var barChartDom = document.getElementById('barChart');
        var barChart = echarts.init(barChartDom);
        var baroption = {
            title: {
                text: `日出栏量趋势`,
                subtext: '单位：头',
                textStyle: {
                    fontSize: 15
                }
            },
            legend: {
                left: 'right'
            },
            grid: {
                left: '1%',
                right: '1%',
                bottom: '10%',
                containLabel: true,
            },
            tooltip: {},
            dataset: {
                source: [
                    ['product', '内销', '外销'],
                    [moment(_today).subtract(6, 'days').format('MM/DD'), inCount[0], outCount[0]],
                    [moment(_today).subtract(5, 'days').format('MM/DD'), inCount[1], outCount[1]],
                    [moment(_today).subtract(4, 'days').format('MM/DD'), inCount[2], outCount[2]],
                    [moment(_today).subtract(3, 'days').format('MM/DD'), inCount[3], outCount[3]],
                    [moment(_today).subtract(2, 'days').format('MM/DD'), inCount[4], outCount[4]],
                    [moment(_today).subtract(1, 'days').format('MM/DD'), inCount[5], outCount[5]],
                    [moment(_today).format('MM/DD'), inCount[6], outCount[6]]
                ]
            },
            xAxis: {
                type: 'category',
                axisLabel: {
                    rotate: 50,
                }
            },
            yAxis: {
                //name:'头',
                type: 'value',
                //axisLabel: {
                //    formatter: '{value} 头'
                //}
            },
            series: [{
                type: 'bar',
                label: {
                    normal: {
                        show: true,
                        position: "top"
                    }
                },
            }, {
                type: 'bar',
                label: {
                    normal: {
                        show: true,
                        position: "top"
                    }
                }
            }]
        };
        baroption && barChart.setOption(baroption);
    }

    const isTop = () => {
        var t = document.documentElement.scrollTop || document.body.scrollTop;
        return t === 0 ? true : false;
    }

})(window, document, jQuery)